package com.ascainiao.paygame.controller;

import com.ascainiao.paygame.RandomValidateCodeUtil;
import com.ascainiao.paygame.mapper.TokenMapper;
import com.ascainiao.paygame.model.Token;
import com.ascainiao.paygame.utils.TokenUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Map;

@RestController
public class ImageCode {
    private static final Logger logger = LoggerFactory.getLogger(ImageCode.class);
    @Autowired
    private TokenMapper tokenMapper;
    /**
     * 生成验证码
     */
    @RequestMapping(value = "/getVerify")
    public void getVerify(HttpServletRequest request, HttpServletResponse response) {
        //生成随机字符串
        String randomString = TokenUtils.generateToken(4);
        //生成长度为32的token
        String tokenStr=TokenUtils.generateToken(32);
        //token实体
        Token token=new Token();
        token.setToken(tokenStr);
        token.setData("{\"code\":\""+randomString+"\"}");
        //设置token有效期
        LocalDateTime now = LocalDateTime.now();
        // 将当前时间增加1小时
        LocalDateTime twentyFourHoursLater = now.plusHours(1);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        token.setExpiry(twentyFourHoursLater.format(formatter));
        tokenMapper.insert(token);
        //设置cookie
        Cookie cookie = new Cookie("Admin-Token", tokenStr);
        cookie.setMaxAge(60 * 60); // 设置cookie有效期为1小时
        response.addCookie(cookie);
        try {
            response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
            response.setHeader("Pragma", "No-cache");//设置响应头信息，告诉浏览器不要缓存此内容
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
            randomValidateCode.getRandcode(request, response,randomString);//输出验证码图片方法
        } catch (Exception e) {
            logger.error("获取验证码失败>>>>   ", e);
        }
    }
    /**
     * 校验验证码
     */
    @RequestMapping(value = "/checkVerify", method = RequestMethod.POST, headers = "Accept=application/json")
    public boolean checkVerify(@RequestBody Map<String, Object> requestMap, HttpSession session) {
        try{
            //从session中获取随机数
            String inputStr = requestMap.get("inputStr").toString();
            String random = (String) session.getAttribute("RANDOMVALIDATECODEKEY");
            if (random == null) {
                return false;
            }
            if (random.equals(inputStr)) {
                return true;
            } else {
                return false;
            }
        }catch (Exception e){
            logger.error("验证码校验失败", e);
            return false;
        }
    }
}
